/**
 * @param {string} num
 * @param {number} k
 * @return {string}
 */
var removeKdigits = function (num, k) {
  let n = num.length, finalAns = [];
  let tempAns = [];
  tempAns.push(num[0]);
  for (let i = 1; i < n; ++i) {
    // 如果某个元素小于前面的元素
    while (tempAns.length && num[i] < tempAns[tempAns.length - 1] && k > 0) {
      tempAns.pop();
      k--;
    }
    tempAns.push(num[i]);
  }
  // 剔除掉最后一个元素
  for (let i = 0; i < k; ++i) {
    tempAns.pop();
  }
  // 如果此时已经没有元素了，就返回0
  if (!tempAns.length) {
    return "0";
  } else {
    let ans = [];
    // 将tempAns装入
    while (tempAns.length) {
      ans.push(tempAns[tempAns.length - 1]);
      tempAns.pop();
    }
    // 逆序
    for (let i = ans.length - 1; i >= 0; --i) {
      finalAns.push(ans[i]);
    }
    // 删掉前缀0
    while (finalAns[0] == '0') {
      finalAns = finalAns.slice(1, finalAns.length);
    }
    if (!finalAns.length) {
      return "0";
    }
    return finalAns.join("");
  }
};
let num = "1432219",
  k = 3;
console.log(removeKdigits(num, k));
num = "10200", k = 1;
console.log(removeKdigits(num, k));
num = "10", k = 2;
console.log(removeKdigits(num, k));
num = "112", k = 1;
console.log(removeKdigits(num, k));
num = "10", k = 1;
console.log(removeKdigits(num, k));
